<template>
	<div class="ivvr-container">
		<p class="nlpSetting add">
			<el-button class="" @click="addIntentionBranch" v-if="isShowIntention && !showDetail && ivvrOptions.length === 0" :disabled="nluError">新增一个特定意图分支</el-button>
		</p>
		<template v-if="ivvrOptions.length !== 0">
			<div class="answer" v-for="(item, index) in ivvrOptions" :key="index">
				<el-form-item v-if="item.checkedAnswer" :label="`回答分支${index + 1} `" :prop="`${prop}.${index}.answerIntentionSelect`" required="true" :rules="rules.answerIntentionSelect">
					<el-select
						v-model="item.answerIntentionSelect"
						:disabled="showDetail"
						placeholder="请选择意图点"
						@change="onChangeIntenLibary"
						class="intention-select"
						id="intention-select"
						style="width: 260px"
					>
						<el-option v-for="(sItem, sIndex) in intentionDotList" :key="sIndex" :label="sItem.note" :value="sItem.intent"></el-option>
					</el-select>
				</el-form-item>

				<span class="checkbox">
					<el-checkbox v-model="item.checkedAnswer" :disabled="showDetail" @change="onCheckBox(index)">NLU</el-checkbox>
				</span>

				<el-form-item v-if="item.checkedAnswer === false" :label="`回答分支${index + 1} `" :prop="`${prop}.${index}.answerIntention`" :rules="rules.answerIntention">
					<el-input
						v-model="item.answerIntention"
						:disabled="showDetail"
						@input="e => (item.answerIntention = validForbid(e))"
						maxlength="140"
						placeholder="请输入意图点"
						@change="onChange('intention.' + index + '.answerIntention')"
						style="width: 260px"
					>
					</el-input>
				</el-form-item>

				<AiSpeak
					:rules="rules.answerSpeak"
					:variableIcon="true"
					:required="false"
					:disabled="showDetail"
					:value="item.answerSpeak"
					:validateStatus="item.answerSpeakValidate"
					:video="item.video"
					@clearVideo="clearVideo(index)"
					:textArea="true"
					:label="'AI说'"
					@input="(e, val) => input(e, val, index)"
					placeholder="请编辑AI客服播报的话术"
					@showVideoTable="showVideoTable(index)"
					@onAddVariable="onAddVariable(index)"
					:id="'answerSpeak' + index"
					:prop="`${prop}_${index}_answerSpeak`"
					@change="onChange('intention_' + index + '_answerSpeak')"
					style="width: 480px"
				/>
				<el-form-item label="下一步" :prop="`${prop}.${index}.nextStepsAnswer`" class="nextBotton" required="true" :rules="rules.nextStepsAnswer">
					<el-select
						v-model="item.nextStepsAnswer"
						:disabled="showDetail"
						placeholder="下一步操作"
						@change="onChange('intention.' + index + '.nextStepsAnswer')"
						class="intention-select"
						id="intention-select"
					>
						<el-option v-for="item in nextStepOption" :key="item.value" :label="item.taskName" :value="item.taskId"> </el-option>
					</el-select>
				</el-form-item>
				<div class="btn" v-if="!showDetail">
					<img @click="deleteIntention(index)" class="del-btn" :src="deleteImage" />
					<img @click="addIntention" class="add-btn" :src="insertImage" v-if="isActiveIcon && index === ivvrOptions.length - 1 && index !== 4" />
				</div>
				<VideoTable
					v-if="tableVideoDialog"
					:tableVideoDialog="tableVideoDialog"
					:videoType="tableVideoType"
					:videoSlect="selectVideoIndex[inputCurrIndex]"
					@ok="sureVideoData"
					@cancel="cancelVideoData"
					:showDetail="showDetail"
				/>
				<!-- 用户变量 -->
				<UserAttribute v-if="isShowUserAttribute" :dialogVisible="isShowUserAttribute" @on-ok="onChosseUserAttribute" @on-cancel="onCloseUserAttribute" />
			</div>
		</template>
	</div>
</template>

<script>
import { getIntentLibaryList, getIntentDotList } from '@/api/api.js';
import AiSpeak from '../AiSpeak/index.vue';
import UserAttribute from './UserAttribute.vue';
import VideoTable from '@/views/components/VideoTable.vue';
import { insertStr } from '@/utils/tool';
import delGroupImg from '@/assets/img/icon/del_group.png';
import addGroupImg from '@/assets/img/icon/add_group.png';
import aivideoErrorImg from '@bpmn/assets/img/aivideoError.png';
import aivideoImg from '@bpmn/assets/img/aivideo.png';
export default {
	name: '',
	components: {
		AiSpeak,
		VideoTable,
		UserAttribute
	},
	props: {
		nextStepOption: {
			type: Array,
			default: () => [],
			required: true
		},
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},

		showDetail: {
			type: Boolean,
			default: () => false
		},
		videoIcon: {
			type: String,
			default: () => ''
		},
		nluError: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		const vaildateRepeats = (rule, value, callback) => {
			let arr = this.ivvrOptions.filter(item => item.answerIntention === value);
			console.log(arr);
			if (arr.length > 1) {
				return callback(new Error('该回答分支已被使用，请输入别的回答分支'));
			}
			return callback();
		};
		// todo 选择意图点下拉框 去重校验
		const vaildateanswerIntentionSelect = (rule, value, callback) => {
			let arr = this.ivvrOptions.filter(item => item.answerIntentionSelect === value);
			console.log(arr);
			if (arr.length > 1) {
				return callback(new Error('该回答分支已被使用，请选择别的回答分支'));
			}
			return callback();
		};

		const vaildateVideo = (rule, value, callback) => {
			this.ivvrOptions.map(ivvr => {
				if (ivvr.answerSpeak && !ivvr.video) {
					ivvr.answerSpeakValidate = false;
					return callback(new Error('请选择播报视频'));
				}
				ivvr.answerSpeakValidate = true;
				return callback();
			});
		};

		return {
			intentLib: [], // 意图库列表
			intentionDotList: [], // 意图点列表
			intentLibName: '',
			ivvrOptions: [],
			isShowAnswerYes: false, // 回答分支
			isActiveIcon: true, // icon图标显示隐藏
			isShowIntention: true,
			isShowUserAttribute: false,
			deleteImage: delGroupImg,
			insertImage: addGroupImg,
			errorVideo: aivideoErrorImg,
			videoSelectIcon: aivideoImg,

			// currIndex: null,
			currVariableindex: null,
			inputCurrIndex: null,
			tableVideoDialog: false,
			// 验证规则校验

			selectVideoIndex: [],
			rules: {
				nextStepsAnswer: [
					{
						required: true,
						message: '请选择下一步操作',
						trigger: 'change'
					}
				],
				answerIntentionSelect: [
					{
						required: true,
						message: '请选择意图点',
						trigger: ['blur', 'change']
					},
					{ validator: vaildateanswerIntentionSelect, trigger: ['blur', 'change'] }
				],
				answerIntention: [
					{
						required: true,
						message: '请输入意图点',
						trigger: ['blur', 'change']
					},
					{ validator: vaildateRepeats, trigger: ['blur', 'change'] }
				],
				answerSpeak: [{ validator: vaildateVideo, trigger: ['blur', 'change'] }]
			}
		};
	},
	watch: {
		value(val) {
			this.$nextTick(() => {
				this.getIntentLib();
			});
		}
	},
	mounted() {
		this.getIntentLib();
		// eslint-disable-next-line vue/no-mutating-props
		this.updateVideo = this.sureVideoData;
		console.log(this.prop);
	},
	methods: {
		// 新增特定意图分支
		addIntentionBranch() {
			this.isShowAnswerYes = true;
			this.isShowIntention = false;
			if (this.ivvrOptions.length === 0) {
				let intention = {
					answerIntention: '',
					answerSpeak: '',
					nextStepsAnswer: '',
					checkedAnswer: true,
					name: '',
					answerSpeakVariableId: '',
					answerSpeakVariables: [],
					answerIntentionSelect: '',
					video: '',
					answerSpeakValidate: true
				};
				this.ivvrOptions.push(intention);
				this.$emit('input', this.prop, this.ivvrOptions);
			}
		},
		// + 号icon 添加回答分支
		addIntention() {
			let intention = {
				answerIntention: '',
				answerSpeak: '',
				nextStepsAnswer: '',
				checkedAnswer: true,
				name: '',
				answerSpeakVariableId: '',
				answerSpeakVariables: [],
				answerIntentionSelect: '',
				video: '',
				answerSpeakValidate: true
			};
			this.ivvrOptions.push(intention);
			this.$emit('input', this.prop, this.ivvrOptions);
		},
		// 删除意图分支
		deleteIntention(index) {
			if (this.ivvrOptions.length - 1 === 0) {
				this.isShowIntention = true;
				this.isShowAnswerYes = false;
			}
			this.ivvrOptions.splice(index, 1);
			this.$emit('input', this.prop, this.ivvrOptions);
		},
		// 获取意图库和意图点
		getIntentLib() {
			// 调用意图库接口
			getIntentLibaryList('ivvr', 1, 100)
				.then(res => {
					console.log(res.data);
					this.intentLib = res.data.intentlibs;
					this.intentLib.forEach(item => {
						this.intentLibName = item.intentlib;
					});

					// 调用意图点接口
					getIntentDotList(this.intentLibName, 1, 100)
						.then(response => {
							console.log(response.data);
							this.intentionDotList = response.data.intentsInNlu;
							this.ivvrOptions = [...this.value];
							console.log(this.ivvrOptions);
						})
						.catch(err => {
							this.$message.error('获取意图库失败');
							console.log(err);
						});
				})
				.catch(err => {
					this.$message.error('获取意图库失败');
					console.log(err);
				});
		},
		onChange() {},
		onChosseUserAttribute(data, businessData) {
			console.log(data);
			// const parentNode = document.getElementById(`answerSpeak${this.currVariableindex}`);
			// const wordsDom = parentNode.getElementsByClassName('el-textarea__inner');
			let wordsDom = document.getElementById(`${this.prop}_${this.currVariableindex}_answerSpeak`);
			if (!wordsDom) {
				wordsDom = document.getElementById(`${this.prop}_${this.currVariableindex}_answerSpeaktextarea`);
			}
			console.log(wordsDom);
			let variable = '';
			if (data && data.bizscenario_role && data.bizscenario_role.name) {
				variable = `{{客户信息_${data.bizscenario_role.name}_${data.name}_${data.id}}}`;
				this.ivvrOptions[this.currVariableindex].answerSpeakVariableId = data.id;
				this.ivvrOptions[this.currVariableindex].answerSpeakVariables.push(data);
			} else {
				variable = `{{业务信息_${businessData.name}_${businessData.id}}}`;
				this.ivvrOptions[this.currVariableindex].answerSpeakVariableId = businessData.id;
				this.ivvrOptions[this.currVariableindex].answerSpeakVariables.push(businessData);
			}
			this.ivvrOptions[this.currVariableindex].answerSpeak = insertStr(this.ivvrOptions[this.currVariableindex].answerSpeak, wordsDom, variable);

			this.inputCurrIndex = this.currVariableindex;
			this.$emit('input', this.prop, this.ivvrOptions);
			this.isShowUserAttribute = false;
		},
		showVideoTable(index) {
			this.inputCurrIndex = index;
			this.tableVideoDialog = true;
			console.log(this.ivvrOptions);
		},
		cancelVideoData() {
			this.tableVideoDialog = false;
		},
		sureVideoData(id, video) {
			this.ivvrOptions[this.inputCurrIndex].video = video;
			this.tableVideoDialog = false;
			this.selectVideoIndex[this.inputCurrIndex] = id;
		},
		input(prop, val, index) {
			this.ivvrOptions[index].answerSpeak = val;
			this.inputCurrIndex = index;
			this.$emit('input', this.prop, this.ivvrOptions);
		},
		clearVideo(index) {
			console.log(this.ivvrOptions);
			this.ivvrOptions[index].video = '';
			this.selectVideoIndex[index] = null;
			this.$emit('input', this.prop, this.ivvrOptions);
		},
		onAddVariable(index) {
			this.isShowUserAttribute = true;
			this.currVariableindex = index;
		},

		onCloseUserAttribute() {
			this.isShowUserAttribute = false;
		},
		onCheckBox(index) {
			console.log(index);
			if (this.ivvrOptions[index].checkedAnswer) {
				this.ivvrOptions[index].answerIntention = '';
			} else {
				this.ivvrOptions[index].answerIntentionSelect = '';
			}
		}
	}
};
</script>

<style lang="less" scoped>
.add {
	position: relative;
	text-align: left;
	left: 0;
	top: 0;
	padding-top: 10px;
	padding-bottom: 10px;
}
.answer {
	padding-top: 20px;
	width: calc(100% - 50px);
	// height: 168px;
	background-color: #f9f9f9;
	margin-top: 15px;
	position: relative;
	padding-bottom: 5px;
	.checkbox {
		position: absolute;
		right: 8px;
		top: 28px;
	}
	.intention-select {
		width: 306px;
	}
	.el-input {
		width: 260px;
	}
}

.btn {
	position: relative;
}
.add-btn {
	position: absolute;
	top: -15px;
	right: -30px;
}
.del-btn {
	position: absolute;
	top: -203px;
	right: -30px;
}
</style>
